package com.shop.front.service.store;

import com.alibaba.fastjson.JSON;
import com.shop.front.consts.FrontConst;
import com.shop.front.response.FrontRetEnum;
import com.shop.front.vo.store.*;
import com.shop.common.enums.System.NewSystemConfigEnum;
import com.shop.common.enums.TrueFalseEnum;
import com.shop.common.enums.pay.PayBusinessEnum;
import com.shop.common.enums.pay.PayStatusEnum;
import com.shop.common.enums.pay.PayTypeEnum;
import com.shop.common.enums.store.StoreOrderStatusChangeTypeEnum;
import com.shop.common.enums.store.StoreOrderStatusEnum;
import com.shop.common.enums.store.StoreProductEnum;
import com.shop.common.enums.user.AccountTypeEnum;
import com.shop.common.enums.user.BillTableNameEnum;
import com.shop.common.enums.user.IncomeTypeEnum;
import com.shop.domain.store.*;
import com.shop.domain.system.NewSystemConfig;
import com.shop.domain.user.User;
import com.shop.front.dao.store.*;
import com.shop.front.dao.user.UserDao;
import com.shop.front.request.store.StoreOrderCartInfoSubmitReq;
import com.shop.front.request.store.StoreOrderSubmitReq;
import com.shop.front.service.pay.PayService;
import com.shop.front.service.system.SystemService;
import com.shop.front.service.user.UserBillService;
import com.shop.front.service.user.UserIntegtralBillService;
import com.shop.front.service.user.UserPinkBillService;
import com.shop.util.BeanCopyUtils;
import com.shop.util.IdSignUtil;
import com.shop.util.RandomUtil;
import com.shop.web.cache.RedisCache;
import com.shop.web.exception.AmountNotEnoughException;
import com.shop.web.exception.GCRuntimeException;
import com.shop.web.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
@Transactional
public class StoreOrderService {

    @Autowired
    private StoreProductDao storeProductDao;
    @Autowired
    private StoreProductAttrValueDao storeProductAttrValueDao;
    @Autowired
    private StoreCartDao storeCartDao;
    @Autowired
    private StoreOrderDao storeOrderDao;
    @Autowired
    private StoreOrderCartInfoDao storeOrderCartInfoDao;
    @Autowired
    private StoreOrderCartInfoSQLDao storeOrderCartInfoSQLDao;
    @Autowired
    private StoreOrderSQLDao storeOrderSQLDao;
    @Autowired
    private PayService payService;
    @Autowired
    private StoreOrderStatusDao storeOrderStatusDao;
    @Autowired
    private UserBillService userBillService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserIntegtralBillService userIntegtralBillService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private UserPinkBillService userPinkBillService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 我的订单统计
     *
     * @return
     */
    public BaseResponse myOrderStatistic(Long userId) {
        StoreOrderUserStatisticVo orderUserStatisticVo = storeOrderSQLDao.myOrderStatistic(userId);
        return new BaseResponse(orderUserStatisticVo);
    }

    /**
     * 我的订单
     *
     * @return
     */
    public BaseResponse myOrder(Long userId, Integer status) {
        Page<StoreOrderVo> page = storeOrderSQLDao.myOrder(userId, status);
        List<StoreOrderCartInfoVo> orderCartInfoList = null;
        for (StoreOrderVo orderVo : page.getContent()) {
            orderCartInfoList = storeOrderCartInfoSQLDao.orderCartInfoList(orderVo.getId());
            orderVo.setOrderCartInfoList(orderCartInfoList);
        }
        return new BaseResponse(page);
    }

    /**
     * 订单详情
     *
     * @return
     */
    public BaseResponse info(Long id) {
        StoreOrder order = storeOrderDao.findSingle(id);
        StoreOrderVo orderVo = new StoreOrderVo();
        try {
            BeanCopyUtils.copyProperties(orderVo, order);
        } catch (Exception e) {
            log.error("返回订单详情赋值异常！", e);
        }

        // 查询商品清单
        List<StoreOrderCartInfoVo> orderCartInfoList = storeOrderCartInfoSQLDao.orderCartInfoList(id);
        orderVo.setOrderCartInfoList(orderCartInfoList);

        return new BaseResponse(orderVo);
    }

    /**
     * 订单详情
     *
     * @return
     */
    public BaseResponse infoByOrderNo(String orderNo) {
        StoreOrder order = storeOrderDao.findByOrderNo(orderNo);
        StoreOrderVo orderVo = new StoreOrderVo();
        try {
            BeanCopyUtils.copyProperties(orderVo, order);
        } catch (Exception e) {
            log.error("返回订单详情赋值异常！", e);
        }

        // 查询商品清单
        List<StoreOrderCartInfoVo> orderCartInfoList = storeOrderCartInfoSQLDao.orderCartInfoList(order.getId());
        orderVo.setOrderCartInfoList(orderCartInfoList);

        return new BaseResponse(orderVo);
    }

    /**
     * 订单详情
     *
     * @return
     */
    public StoreOrderUserDetailVo infoDetailByOrderNo(String orderNo) {
        StoreOrder order = storeOrderDao.findByOrderNo(orderNo);
        log.info("order:" + order);
        StoreOrderUserDetailVo orderVo = new StoreOrderUserDetailVo();
        try {
            BeanCopyUtils.copyProperties(orderVo, order);
        } catch (Exception e) {
            log.error("返回订单详情赋值异常！", e);
        }

        // 查询商品清单
        StoreOrderCartInfoVo orderCartInfo = storeOrderCartInfoSQLDao.orderCartInfoObj(order.getId());
        orderVo.setOrderCartInfoObj(orderCartInfo);

        // 查询用户信息
        User user = userDao.findSingle(order.getUid());
        orderVo.setUser(user);

        return orderVo;
    }

    /**
     * 提交订单
     *
     * @return
     */
    public BaseResponse submit(Long userId, StoreOrderSubmitReq req) {
        int totalNum = 0;
        BigDecimal totalPrice = BigDecimal.ZERO;
        BigDecimal totalIntegral = BigDecimal.ZERO;
        BigDecimal totalPostage = BigDecimal.ZERO;

        // 付款类型校验
        PayTypeEnum payTypeEnum = PayTypeEnum.val(req.getPayCode());
        if (null == payTypeEnum) {
            return BaseResponse.fail("请选择支付方式！");
        }

        // 遍历商品批量校验
        Set<Long> productIds = new HashSet<>();
        Long cartId = null;
        StoreCart storeCart = null;
        StoreProduct product = null;
        StoreProductAttrValue productAttrValue = null;
        User user = userDao.findSingle(userId);

        // 商品列表
        if (null == req.getCartInfoList() || req.getCartInfoList().size() <= 0) {
            return BaseResponse.fail("请先选择一个商品！");
        }

        for (StoreOrderCartInfoSubmitReq orderCartInfoReq : req.getCartInfoList()) {
            // 购物车数量必须大于0
            if (null == orderCartInfoReq.getCartNum() || orderCartInfoReq.getCartNum() <= 0) {
                return BaseResponse.fail("商品数量有误！");
            }

            // 购物车商品信息
            cartId = IdSignUtil.checkSign(orderCartInfoReq.getSign());
            if (null == cartId) {
                log.error("购物车提交订单，解析购物车商品ID异常！sign -> {}", orderCartInfoReq.getSign());
                return BaseResponse.ILLEGAL_REQUEST;
            }
            storeCart = storeCartDao.findSingle(cartId);
            if (null == storeCart) {
                log.error("购物车提交订单，获取购物车商品信息为空！cartId -> {}", cartId);
                return BaseResponse.ILLEGAL_REQUEST;
            }
            if (TrueFalseEnum.FALSE.getCode() != storeCart.getIsPay()) {
                //log.error("请勿重复发起支付！若未支付成功，请重新创建订单！cartId -> {}", cartId);
                return BaseResponse.fail("请勿重复发起支付！若未支付成功，请重新创建订单！");
            }
            orderCartInfoReq.setCart(storeCart);

            // 商品信息
            product = storeProductDao.findSingle(storeCart.getProductId());
            if (null == product) {
                log.error("购物车提交订单，获取商品信息为空！productId -> {}", storeCart.getProductId());
                return BaseResponse.ILLEGAL_REQUEST;
            }
            orderCartInfoReq.setProduct(product);

            // 商品规格信息
            productAttrValue = storeProductAttrValueDao.findSingle(storeCart.getProductAttrValueId());
            if (null == productAttrValue) {
                log.error("购物车提交订单，获取商品规格信息为空！productAttrValueId -> {}", storeCart.getProductAttrValueId());
                return BaseResponse.ILLEGAL_REQUEST;
            }
            orderCartInfoReq.setProductAttrValue(productAttrValue);

            // 商品是否下架
            if (req.getStorePink() == null) {
                if (TrueFalseEnum.TRUE.getCode() != product.getIsShow()) {
                    return BaseResponse.fail("商品非上架状态!");
                }
            }

            // 商品该规格是否库存不足
            if (productAttrValue.getStock() < orderCartInfoReq.getCartNum()) {
                return BaseResponse.fail("商品库存不足!");
            }

            // 是否包含多种商品（当前暂不支持多种商品下单）
            if (productIds.size() > 0 && !productIds.contains(product.getId())) {
                return BaseResponse.fail("提交订单只能选择同一类商品!");
            } else {
                productIds.add(product.getId());
            }

            // 是否充值商品
            if (product.getId().equals(StoreProductEnum.RECHARGE.getId())) { // 是
                // 判断支付方式
                if (!payTypeEnum.isCash()) { // 非现金方式
                    return BaseResponse.fail("该商品暂不支持此支付方式，请更换其他支付方式！");
                }
            }

            //积分商品 验证积分是否足够

            // 累计数量和总额
            totalNum += orderCartInfoReq.getCartNum();
            totalPrice = totalPrice.add(productAttrValue.getPrice().multiply(new BigDecimal(orderCartInfoReq.getCartNum())));


        }

        // 创建订单
        String orderNo = RandomUtil.generateId7OrderNo("C", userId);
        if (null != req.getStorePink()) {
            orderNo = req.getStorePink().getOrderNo();
        }

        if (null != req.getStoreSnapPink()) {
            orderNo = req.getStoreSnapPink().getOrderNo();
        }

        StoreOrder order = new StoreOrder();
        order.setTotalPrice(totalPrice);
        if (null != req.getStorePink()) {
            order.setTotalPrice(req.getStorePink().getTotalPrice());
        }
        if (null != req.getStoreSnapPink()) {
            order.setTotalPrice(req.getStoreSnapPink().getTotalPrice());
        }


        order.setOrderNo(orderNo);
        order.setUid(userId);
        order.setTotalNum(totalNum);
        order.setTotalPostage(totalPostage);
        order.setPayCode(payTypeEnum.getCode());
        order.setPayType(payTypeEnum.getType());
        order.setUserPhone(req.getUserPhone());
        order.setRealName(req.getRealName());
        order.setUserAddress(req.getUserAddress());
        order.setRemark(req.getRemark());
        // 购物车中拼团产品，目前都是一样的，直接使用最后一个商品的所属拼团信息
        order.setPinkId(storeCart.getPinkId());
        order.setStorePinkId(storeCart.getStorePinkId());
        storeOrderDao.save(order);

        // 保存订单状态
        StoreOrderStatus orderStatus = new StoreOrderStatus();
        orderStatus.setOid(order.getId());
        orderStatus.setChangeType(StoreOrderStatusChangeTypeEnum.CACHE_KEY_CREATE_ORDER.getKey());
        orderStatus.setChangeMessage(StoreOrderStatusChangeTypeEnum.CACHE_KEY_CREATE_ORDER.getMessage());
        storeOrderStatusDao.save(orderStatus);

  /*      if(TrueFalseEnum.TRUE.getCode() == storeCart.getIsIntegral()){

            //扣除积分
            int subtractRows = userDao.subtractIntegral(userId, totalIntegral);
            if(subtractRows <= 0) {
                throw new AmountNotEnoughException(FrontRetEnum.USER_INTEGRAL_NOT_ENOUGH);
            }
            //增加积分记录流水
            BigDecimal refreshIntegral = user.getIntegral().subtract(totalIntegral);
            userIntegtralBillService.addUserIntegralBill(userId, order.getId(), user.getIntegral(),totalIntegral,refreshIntegral,
                    BillTableNameEnum.INTEGRAL_ORDER.getKey(),IncomeTypeEnum.EXPEND.getKey(),  "购买商品，扣除积分" + totalIntegral);
        }*/

        // 遍历处理订单
        int rows = 0;
        int cartNum = 0;
        Long productId = null;
        Long productAttrValueId = null;
        StoreOrderCartInfo orderCartInfo = null;    // 订单清单
        StoreCartInfoVo cartInfoVo = null;
        for (StoreOrderCartInfoSubmitReq orderCartInfoReq : req.getCartInfoList()) {
            productId = orderCartInfoReq.getProduct().getId();
            productAttrValueId = orderCartInfoReq.getProductAttrValue().getId();
            cartNum = orderCartInfoReq.getCartNum();

            // 商品减少库存
            // 若为充值商品，则不扣库存不添加销量
            if (!productId.equals(StoreProductEnum.RECHARGE.getId())) {
                rows = storeProductAttrValueDao.subtractStock(productAttrValueId, cartNum);
                if (rows <= 0) {
                    log.error("提交订单，减少商品库存更新失败！id -> {}, cartNum -> {}", productAttrValueId, cartNum);
                    throw new GCRuntimeException(FrontRetEnum.PRODUCT_STOCK_IS_NOT_ENOUGH);
                }

                // 商品添加销量   随机添加1~6销量
                int sale = (int) (1 + Math.random() * 6);

                Long ruchangQuan = 551L;
                if (ruchangQuan.equals(productId)) {//入场券 销量处理
                    sale = 1;
                }
                //200元抢购商品  拼团减库存  提货不做处理
                if (null != req.getStoreSnapPink()) {
                    sale = 0;
                }
                storeProductAttrValueDao.addSales(productAttrValueId, sale);
                storeProductDao.addSales(productId, sale);
            }

            // 修改购物车状态为“已支付”
            storeCartDao.updateIsPay(orderCartInfoReq.getCart().getId(), TrueFalseEnum.TRUE.getCode());

            // 商品购物车相关信息
            cartInfoVo = new StoreCartInfoVo();
            cartInfoVo.setCart(orderCartInfoReq.getCart());
            cartInfoVo.setProduct(orderCartInfoReq.getProduct());
            cartInfoVo.setStoreProductAttrValue(orderCartInfoReq.getProductAttrValue());

            // 列入清单
            orderCartInfo = new StoreOrderCartInfo();
            orderCartInfo.setCartId(orderCartInfoReq.getCart().getId());
            orderCartInfo.setOid(order.getId());
            orderCartInfo.setProductId(productId);
            orderCartInfo.setProductAttrValueId(productAttrValueId);
            orderCartInfo.setCartNum(cartNum);
            orderCartInfo.setPrice(orderCartInfoReq.getProductAttrValue().getPrice());
            orderCartInfo.setTotalPrice(orderCartInfoReq.getProductAttrValue().getPrice().multiply(new BigDecimal(cartNum)));
            // 拼团订单商品，价格使用
            if (null != req.getStorePink()) {
                orderCartInfo.setPrice(req.getStorePink().getPrice());
                orderCartInfo.setTotalPrice(req.getStorePink().getTotalPrice());
            }
            orderCartInfo.setImage(orderCartInfoReq.getProductAttrValue().getImage());
            orderCartInfo.setStoreName(orderCartInfoReq.getProduct().getStoreName());
            orderCartInfo.setSuk(orderCartInfoReq.getProductAttrValue().getSuk());
            orderCartInfo.setCartInfo(JSON.toJSONString(cartInfoVo));
            storeOrderCartInfoDao.save(orderCartInfo);
        }

        StoreOrderVo orderVo = new StoreOrderVo();
        try {
            BeanCopyUtils.copyProperties(orderVo, order);
        } catch (Exception e) {
            log.error("返回订单信息赋值异常！", e);
        }

        // 订单金额
        BigDecimal orderAmount = order.getTotalPrice();

        // 拼团提货下单
        if (null != req.getStorePink() || null != req.getStoreSnapPink()) {

            //增加积分
            NewSystemConfig newSystemConfig = systemService.getSystemConfig(NewSystemConfigEnum.DELIVERY_GOODS_SEND_INTEGRAL);
            BigDecimal sendIngegral = new BigDecimal(newSystemConfig.getValue());
            userDao.addIntegral(userId, sendIngegral);

            //添加增加积分获得记录
            BigDecimal refreshIntegral = user.getIntegral().add(sendIngegral);
            userIntegtralBillService.addUserIntegralBill(userId, order.getId(), user.getIntegral(), sendIngegral, refreshIntegral,
                    BillTableNameEnum.GET_GOODS_SEND_INTEGRAL.getKey(), IncomeTypeEnum.INCOME.getKey(), "提货商品，获得积分" + sendIngegral);

            return cbPinkSubmit(order.getId(), orderNo, PayStatusEnum.SUCCESS, orderAmount);
        }

        // 支付方式
        BaseResponse resp = null;

        // 微信支付、支付宝支付
        if (PayTypeEnum.WEIXIN == payTypeEnum) {     //微信官方支付

            // 发起支付
            resp = payService.jtDoPay(PayBusinessEnum.STORE_ORDER, userId, order.getId(),
                    orderAmount, order.getOrderNo(), payTypeEnum);

        }else if(PayTypeEnum.DAIFU_WEIXIN == payTypeEnum) {   // 微信官方代付
            Map<String, Object> daifuMap = new HashMap<>();
            daifuMap.put("orderNo", order.getOrderNo());
            return new BaseResponse(daifuMap);
        } else if (PayTypeEnum.YUE == payTypeEnum) {   // 余额支付

            // 扣除余额
            int subtractRows = userDao.subtractBalance(userId, orderAmount);
            if (subtractRows <= 0) {
                throw new AmountNotEnoughException(FrontRetEnum.USER_BALANCE_NOT_ENOUGH);
            }

            //更新之后金额
            BigDecimal refreshPrice = user.getBalance().subtract(orderAmount);

            //增加用户交易流水
            userBillService.addUserBill(userId, orderAmount, order.getId(), BillTableNameEnum.ORDER.getKey(), user.getBalance(),
                    refreshPrice, IncomeTypeEnum.EXPEND.getKey(), AccountTypeEnum.BALANCE.getKey(),
                    "购买商品", "购买商品，扣除余额" + orderAmount + "元");

            // 发起支付成功回调处理
            return this.cbSubmit(order.getId(), orderNo, PayStatusEnum.SUCCESS, orderAmount);

        } else if (PayTypeEnum.COIN == payTypeEnum) {   // TG支付

            // 扣除TG
            int subtractRows = userDao.subtractCoin(userId, orderAmount);
            if (subtractRows <= 0) {
                throw new AmountNotEnoughException(FrontRetEnum.USER_COIN_NOT_ENOUGH);
            }

            //更新之后金额
            BigDecimal refreshPrice = user.getCoin().subtract(orderAmount);

            //增加用户交易流水
            userBillService.addUserBill(userId, orderAmount, order.getId(), BillTableNameEnum.ORDER.getKey(), user.getCoin(),
                    refreshPrice, IncomeTypeEnum.EXPEND.getKey(), AccountTypeEnum.COIN.getKey(),
                    "购买商品", "购买商品，扣除TG" + orderAmount + "元");

            // 发起支付成功回调处理
            return this.cbSubmit(order.getId(), orderNo, PayStatusEnum.SUCCESS, orderAmount);

        } else if (PayTypeEnum.BROKERAGE == payTypeEnum) {   // 佣金支付

            // 佣金支付
            int subtractRows = userDao.subtractBrokerage(userId, orderAmount);
            if (subtractRows <= 0) {
                throw new AmountNotEnoughException(FrontRetEnum.USER_BROKERAGE_NOT_ENOUGH);
            }

            //更新之后金额
            BigDecimal refreshPrice = user.getBrokerage().subtract(orderAmount);

            //增加用户交易流水
            userPinkBillService.addUserPinkBill(userId, order.getId(), 0L, user.getBrokerage(), orderAmount, refreshPrice,
                    BillTableNameEnum.ORDER.getKey(), IncomeTypeEnum.EXPEND.getKey(), "购买商品，扣除佣金" + orderAmount + "元");

            // 发起支付成功回调处理
            return this.cbSubmit(order.getId(), orderNo, PayStatusEnum.SUCCESS, orderAmount);

        } else {
            log.error("支付方式错误！payType -> " + JSON.toJSONString(payTypeEnum));
            throw new GCRuntimeException(FrontRetEnum.PAY_TYPE_IS_NOT_VALID);
        }

        return resp;
    }

    /**
     * 订单支付请求
     *
     * @return
     */
    public BaseResponse checkPayStatus(String orderNo) {
        StoreOrder order = storeOrderDao.findByOrderNo(orderNo);
        if (null == order) {
            log.error("校验订单支付状态，获取订单信息为空！orderNo -> {}", orderNo);
            return new BaseResponse(FrontRetEnum.PAY_NO_NOT_EXISTS);
        }

        // 状态判断
        if (order.getStatus() == StoreOrderStatusEnum.NEED_PAY.getKey()
                || order.getStatus() == StoreOrderStatusEnum.CANCEL.getKey()) {   // 待支付状态
            // 请求获取支付结果
            return payService.jtCbPay(orderNo);
        } else if (order.getStatus() > StoreOrderStatusEnum.NEED_PAY.getKey()) {  // 支付成功后的其他状态
            return new BaseResponse(order);
        } else {  // 订单异常状态
            return BaseResponse.fail("当前订单为" + StoreOrderStatusEnum.val(order.getStatus()).getName() + "状态！");
        }
    }

    /**
     * 拼团下单回调
     *
     * @return
     */
    public BaseResponse cbPinkSubmit(Long id, String orderNo, PayStatusEnum payStatusEnum, BigDecimal payPrice) {
        StoreOrder order = storeOrderDao.findSingle(id);
        if (null == order) {
            log.error("订单支付回调处理，获取订单信息为空！id -> {}", id);
            return new BaseResponse(FrontRetEnum.PAY_NO_NOT_EXISTS);
        }

        // 根据支付状态修改订单状态
        if (PayStatusEnum.SUCCESS == payStatusEnum) {
            int rows = storeOrderDao.updateByPaySuccess(id, orderNo, payPrice);
            if (rows <= 0) {
                return BaseResponse.ALREADY_EXECUTE;
            }

            // 保存订单状态
            StoreOrderStatus orderStatus = new StoreOrderStatus();
            orderStatus.setOid(order.getId());
            orderStatus.setChangeType(StoreOrderStatusChangeTypeEnum.PAY_SUCCESS.getKey());
            orderStatus.setChangeMessage(StoreOrderStatusChangeTypeEnum.PAY_SUCCESS.getMessage());
            storeOrderStatusDao.save(orderStatus);

        } else {
            log.error("拼团订单回调处理，状态为非成功状态！id -> {}, orderNo -> {}, status -> {}", id, orderNo, payStatusEnum.getValue());
            return BaseResponse.fail("支付未成功");
        }

        return new BaseResponse(order);
    }

    /**
     * 订单支付回调
     *
     * @return
     */
    public BaseResponse cbSubmit(Long id, String orderNo, PayStatusEnum payStatusEnum, BigDecimal payPrice) {
        return cbSubmit(id, orderNo, payStatusEnum, payPrice, null);
    }

    /**
     * 订单支付回调
     *
     * @return
     */
    public BaseResponse cbSubmit(Long id, String orderNo, PayStatusEnum payStatusEnum, BigDecimal payPrice, PayTypeEnum payTypeEnum) {
        StoreOrder order = storeOrderDao.findSingle(id);
        if (null == order) {
            log.error("订单支付回调处理，获取订单信息为空！id -> {}, orderNo -> {}", id, orderNo);
            return new BaseResponse(FrontRetEnum.PAY_NO_NOT_EXISTS);
        }

        // 根据支付状态修改订单状态
        if (PayStatusEnum.SUCCESS == payStatusEnum) {
            // 是否特殊商品
            StoreProductEnum storeProductEnum = null;

            // 支付方式
            if (null != payTypeEnum && payTypeEnum.isCash()) {   // 现金支付
                //获取购物车
                List<StoreOrderCartInfo> orderCartInfoList = storeOrderCartInfoDao.findByOid(id);
                if (null != orderCartInfoList) {
                    for (StoreOrderCartInfo orderCartInfo : orderCartInfoList) {
                        storeProductEnum = StoreProductEnum.val(orderCartInfo.getProductId());
                    }
                }
            }

            // 是否充值商品
            if (null != storeProductEnum && StoreProductEnum.RECHARGE == storeProductEnum) { // 是，余额充值
                // 修改订单状态
                int rows = storeOrderDao.updateCompleteByPaySuccess(id, orderNo, payPrice);
                if (rows <= 0) {
                    log.error("订单支付回调处理，修改订单状态失败！已处理？id -> {}, orderNo -> {}", id, orderNo);
                    return BaseResponse.ALREADY_EXECUTE;
                }

                // 保存订单状态
                StoreOrderStatus orderStatus = new StoreOrderStatus();
                orderStatus.setOid(order.getId());
                orderStatus.setChangeType(StoreOrderStatusChangeTypeEnum.USER_TAKE_DELIVERY.getKey());
                orderStatus.setChangeMessage(StoreOrderStatusChangeTypeEnum.USER_TAKE_DELIVERY.getMessage());
                storeOrderStatusDao.save(orderStatus);

                // 添加余额
                User user = userDao.findSingle(order.getUid());
                userDao.addBalance(user.getId(), payPrice);

                //更新之后金额
                BigDecimal refreshPrice = user.getBalance().add(payPrice);

                //增加用户佣金流水
                userBillService.addUserBill(user.getId(), payPrice, order.getId(), BillTableNameEnum.RECHARGE.getKey(), user.getBalance(),
                        refreshPrice, IncomeTypeEnum.INCOME.getKey(), AccountTypeEnum.BALANCE.getKey(),
                        "购买充值商品", "购买充值商品，添加余额" + payPrice + "元");

            } else {    // 普通商品
                int rows = storeOrderDao.updateByPaySuccess(id, orderNo, payPrice);
                if (rows <= 0) {
                    log.error("订单支付回调处理，修改订单状态失败！已处理？id -> {}, orderNo -> {}", id, orderNo);
                    return BaseResponse.ALREADY_EXECUTE;
                }

          /*      //积分商品 增加积分
                if(TrueFalseEnum.TRUE.getCode() == order.getIsIntegral()){
                    //添加积分
                    NewSystemConfig newSystemConfig = systemService.getSystemConfig(NewSystemConfigEnum.INTEGRAL_SHOPPING_BACK_RATE);
                    BigDecimal sendIngegral = (new BigDecimal(newSystemConfig.getValue()).multiply(order.getTotalPrice())).divide(new BigDecimal("100"));

                    User user = userDao.findSingle(order.getUid());

                    userDao.addIntegral(order.getUid(),sendIngegral);

                    //添加增加积分获得记录
                    BigDecimal refreshIntegral = user.getIntegral().add(sendIngegral);
                    userIntegtralBillService.addUserIntegralBill(user.getId(), order.getId(), user.getIntegral(),sendIngegral,refreshIntegral,
                            BillTableNameEnum.INTEGRAL_PAY_ORDER.getKey(),IncomeTypeEnum.INCOME.getKey(),  "积分商品下单，获得积分" + sendIngegral);

                }*/

                // 保存订单状态
                StoreOrderStatus orderStatus = new StoreOrderStatus();
                orderStatus.setOid(order.getId());
                orderStatus.setChangeType(StoreOrderStatusChangeTypeEnum.PAY_SUCCESS.getKey());
                orderStatus.setChangeMessage(StoreOrderStatusChangeTypeEnum.PAY_SUCCESS.getMessage());
                storeOrderStatusDao.save(orderStatus);
            }

        } else if (PayStatusEnum.TIMEOUT == payStatusEnum) {
            int rows = storeOrderDao.updateStatusByPayTimeout(id, orderNo);
            if (rows <= 0) {
                return BaseResponse.ALREADY_EXECUTE;
            }
        } else {
            log.error("订单支付回调处理，状态为非成功状态！id -> {}, orderNo -> {}, status -> {}", id, orderNo, payStatusEnum.getValue());
            return BaseResponse.fail("支付未成功");
        }

        return new BaseResponse(order);
    }

    /**
     * 取消订单
     *
     * @return
     */
    public BaseResponse cancel(Long id) {
        StoreOrder order = storeOrderDao.findSingle(id);
        if (null == order) {
            return new BaseResponse(FrontRetEnum.PAY_NO_NOT_EXISTS);
        }

        // 状态是否为待支付
        if (StoreOrderStatusEnum.NEED_PAY.getKey() != order.getStatus()) {
            return BaseResponse.fail("该订单不是待支付状态，无法取消！");
        }


        //特殊商品 不能取消
        StoreProductEnum storeProductEnum = null;

        //获取购物车
        List<StoreOrderCartInfo> orderCartInfoList = storeOrderCartInfoDao.findByOid(id);
        if (null != orderCartInfoList) {
            for (StoreOrderCartInfo orderCartInfo : orderCartInfoList) {
                storeProductEnum = StoreProductEnum.val(orderCartInfo.getProductId());
            }
        }
        // 是否充值商品
        if (null != storeProductEnum && StoreProductEnum.RECHARGE == storeProductEnum) { // 是，余额充值
            return BaseResponse.fail("充值订单，无法取消！");
        }

        // 根据订单状态为已取消
        int refresh = storeOrderDao.updateStatusByCancel(id);

      /*  //积分商品订单 取消 退回积分
        if(TrueFalseEnum.TRUE.getCode() == order.getIsIntegral() && refresh > 0 ){
            //查询用户
            User user = userDao.findSingle(order.getUid());
            //添加积分
            userDao.addIntegral(order.getUid(),order.getIntegral());
            //添加积分记录
            BigDecimal refreshIntegral = user.getIntegral().add(order.getIntegral());
            userIntegtralBillService.addUserIntegralBill(order.getUid(), order.getId(), user.getIntegral(),order.getIntegral(),refreshIntegral,
                    BillTableNameEnum.CANCEL_INTEGRAL_ORDER.getKey(),IncomeTypeEnum.INCOME.getKey(),  "取消商品订单，返回积分" + order.getIntegral());
        }*/

        return new BaseResponse();
    }


    /**
     * 用户删除订单
     *
     * @return
     */
    public BaseResponse userDel(Long id) {
        StoreOrder order = storeOrderDao.findSingle(id);
        if (null == order) {
            return new BaseResponse(FrontRetEnum.PAY_NO_NOT_EXISTS);
        }

        // 状态是否大于等于待评价
        if (order.getStatus() < StoreOrderStatusEnum.NEED_EVALUATION.getKey()) {
            return BaseResponse.fail("该订单还未完成收货，无法删除！");
        }

        // 状态是否为已删除
        if (TrueFalseEnum.TRUE.getCode() != order.getIsUserDel()) {
            return BaseResponse.fail("该订单已被删除！");
        }

        // 根据订单状态为已取消
        storeOrderDao.updateStatusByUserDel(id);

        // 保存订单状态
        StoreOrderStatus orderStatus = new StoreOrderStatus();
        orderStatus.setOid(order.getId());
        orderStatus.setChangeType(StoreOrderStatusChangeTypeEnum.USER_DELETE.getKey());
        orderStatus.setChangeMessage(StoreOrderStatusChangeTypeEnum.USER_DELETE.getMessage());
        storeOrderStatusDao.save(orderStatus);

        return new BaseResponse();
    }

    /**
     * 确认收货
     *
     * @return
     */
    public BaseResponse confirmReceipt(Long id) {
        StoreOrder order = storeOrderDao.findSingle(id);
        if (null == order) {
            return new BaseResponse(FrontRetEnum.PAY_NO_NOT_EXISTS);
        }

        // 状态是否为待支付
        if (StoreOrderStatusEnum.NEED_TAKE_DELIVERY.getKey() != order.getStatus()) {
            return BaseResponse.fail("该订单不是待收货状态，无法收货！");
        }

        // 根据订单状态为已取消
        storeOrderDao.updateConfirmReceipt(id);

        // 保存订单状态
        StoreOrderStatus orderStatus = new StoreOrderStatus();
        orderStatus.setOid(order.getId());
        orderStatus.setChangeType(StoreOrderStatusChangeTypeEnum.USER_TAKE_DELIVERY.getKey());
        orderStatus.setChangeMessage(StoreOrderStatusChangeTypeEnum.USER_TAKE_DELIVERY.getMessage());
        storeOrderStatusDao.save(orderStatus);

        return new BaseResponse();
    }

    public BaseResponse orderCartInfo(Long id) {
        StoreOrderCartInfo orderCartInfo = storeOrderCartInfoDao.findSingle(id);
        return new BaseResponse(orderCartInfo);
    }


    /**
     * 去支付
     *
     * @param orderNo
     * @return
     */
    public BaseResponse goPay(String orderNo) {
        StoreOrder order = storeOrderDao.findByOrderNo(orderNo);
        if (null == order) {
            return BaseResponse.fail("订单不存在");
        }

        if (order.getStatus() != StoreOrderStatusEnum.NEED_PAY.getKey()) {
            return BaseResponse.fail("订单状态不是未支付订单");
        }

        Object wxPay = redisCache.get(FrontConst.USER_PAY_SOTRE_ORDER + orderNo);
        if (null == wxPay) {
            return BaseResponse.fail("订单支付超时，请重新下单支付");
        }
        return new BaseResponse(wxPay);
    }

    /**
     * 关闭待支付订单
     *
     * @param orderNo
     */
    public void closeStoreOrderNotPay(String orderNo) {

        StoreOrder order = storeOrderDao.findByOrderNo(orderNo);
        if (null == order) {
            return;
        }
        // 状态判断
        if (order.getStatus() == StoreOrderStatusEnum.NEED_PAY.getKey()) {
            order.setStatus(StoreOrderStatusEnum.CANCEL.getKey());
            storeOrderDao.save(order);
            log.info("orderNo:{}超时未支付失效，关闭订单", orderNo);
        }

    }
}
